package com.eastfair.venuebooking.service.impl;

import com.eastfair.core.exception.BizException;
import com.eastfair.venuebooking.service.MeetAdService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 展览会议系统 展会服务.
 *
 * @author dqq
 * @date 2023 /3/22
 */
@Service
@Slf4j
public class MeetAdServiceImpl implements MeetAdService {

    @Value("${xmmeet.properties.host}")
    private String meetHost;

    @Value("${xmmeet.properties.sync-exh-code}")
    private String syncExhCode;

    @Resource
    private RestTemplate restTemplate;

    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public String syncExhCode(String meetExhId, String exhibitionId) throws Exception {
        log.info("syncExhCode - 同步展会ID到展览会议系统, meetExhId={}, exhibitionId={}", meetExhId, exhibitionId);
        String url = meetHost + syncExhCode;
        Map<String, String> body = new HashMap<>(16);
        body.put("exhid", meetExhId);
        body.put("code", exhibitionId);
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(body);

        log.info("syncExhCode - 调用展览会议同步展会code接口, utl={}, httpEntity={}", url, httpEntity);
        String result = restTemplate.postForObject(url, httpEntity, String.class);
        log.info("syncExhCode - 调用展览会议同步展会code完成, result={}", result);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode resultJsonNode = objectMapper.readTree(result);
        if (resultJsonNode != null && !resultJsonNode.isNull()) {
            String code = resultJsonNode.get("code").asText();
            if (!"200".equals(code)) {
                log.error("调用展览会议同步展会code失败:" + result);
                throw BizException.wrap(1001, "同步展会code到展览会议失败");
            }
        }
        return result;
    }

    @Override
    public void asyncSyncExhCode(String meetExhId, String exhibitionId) {
        log.info("asyncSyncExhCode - 异步同步展会ID到展览会议系统, meetExhId={}, exhibitionId={}", meetExhId, exhibitionId);
        threadPoolTaskExecutor.execute(() -> {
            try {
                syncExhCode(meetExhId, exhibitionId);
            } catch (Exception e) {
                log.error("调用展览会议同步展会code接口失败", e);
            }
        });
    }
}